package com.system.service.impl;

import com.system.dao.IConsumerDao;
import com.system.entity.Consumer;
import com.system.service.IConsumerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class ConsumerServiceImpl implements IConsumerService {

    @Resource
    private IConsumerDao consumerDao;

    @Value("${spring.mail.username}")
    private String sendName;

    @Autowired
    JavaMailSender javaMailSender;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<Consumer> findAll() {
        return consumerDao.findAll();
    }

    @Override
    public Consumer findByCid(Integer cid) {
        return consumerDao.findByCid(cid);
    }

    @Override
    public int saveConsumer(Consumer consumer) {
        return consumerDao.saveConsumer(consumer);
    }

    @Override
    public int updateConsumer(Consumer consumer) {
        return consumerDao.updateConsumer(consumer);
    }

    @Override
    public int deleteConsumer(int cid) {
        return consumerDao.deleteConsumer(cid);
    }

    @Override
    public Consumer login(String cname, String cpass) {
        return consumerDao.login(cname,cpass);
    }

    @Override
    public Integer sendMail(String email) {

        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(sendName);
        simpleMailMessage.setTo(email);
        simpleMailMessage.setSubject("验证码发送");

        int r = (int) ((Math.random()*8998)+1000+1);
        System.out.println(r);
        simpleMailMessage.setText("验证码：" + r);

        try {
            javaMailSender.send(simpleMailMessage);
            System.out.println(redisTemplate);
            redisTemplate.opsForValue().set(email,""+r);
            redisTemplate.expire(email,60*15, TimeUnit.SECONDS);
            return 1;
        }catch (Exception e){
            System.out.println(e.getMessage());
            return 0;
        }

    }

    @Override
    public Consumer findByEmail(String email) {
        return consumerDao.findByEmail(email);
    }
}
